//
//  ContactNoteViewController.m
//  SSNDB
//
//  Created by nako on 9/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ContactNoteViewController.h"
#import "SSNDBAppDelegate.h"
#import	"ContactListViewController.h"

@implementation ContactNoteViewController

@synthesize textViewNote;
@synthesize thisContactList;
@synthesize editButton;
@synthesize saveButton;

/* ------------------------------------------- */

- (void) setThisContactList:(Contact *)paramValue{
	if (thisContactList != nil){
		[thisContactList release];
		thisContactList = nil;
	}
	thisContactList = [[Contact alloc] initWithName:paramValue.SSN contact_date:paramValue.Contact_date note:paramValue.Note];
	//NSLog(@"%@ %@ %@",thisContactList.SSN, thisContactList.Contact_date, thisContactList.Note);
}

- (void) performEdit:(id)paramSender{
	//NSLog(@"----------------%@",__FUNCTION__);
	[self.textViewNote resignFirstResponder];
	[self setDefaultNavigationBarButtons];
}

/* ------------------------------------------- */

- (BOOL)textViewShouldBeginEditing :(UITextView *)textView{
	
	BOOL result = YES;
	
	/* Make sure we create the Done button on the top
	 right hand side of the navigation bar when we are
	 editing the contents of our text view */
	
	if (self.editing == NO){
		[self setEditingModeNavigationBarButtons];
	}
	
	return(result);
	
}
/* ------------------------------------------- */

- (void) setDefaultNavigationBarButtons{
	
	/* By default, we have to have a Save button on the top
	 right hand side of the navigation bar */
	
	[self.navigationItem setRightBarButtonItem:self.editButton
									  animated:YES];
	
	[self setEditing:NO];
	
}

/* ------------------------------------------- */

- (void) setEditingModeNavigationBarButtons{
	
	/* When editing the text fields, we will replace the
	 Save button with a Done button that will resign all
	 text fields from being the first responder just
	 so that the keyboard (if shown) will be hidden */
	
	[self.navigationItem setRightBarButtonItem:self.saveButton
									  animated:YES];
	
	[self setEditing:YES];
	
}


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

- (void) displayAlertWithTitle:(NSString *)paramTitle
                       message:(NSString *)paramMessage{
	
	/* Simply create and display an alert view using
	 the title and the message given to us */
	UIAlertView *alertView = 
	[[[UIAlertView alloc]
	  initWithTitle:paramTitle
	  message:paramMessage
	  delegate:nil
	  cancelButtonTitle:NSLocalizedString(@"OK", nil)
	  otherButtonTitles:nil, nil] autorelease];
	
	[alertView show];
	
}
/* ------------------------------------------- */

- (void)  performSaveNote:(id)paramSender{
	
	NSLog(@"%@ %@ %@",thisContactList.SSN, thisContactList.Contact_date, thisContactList.Note);
	/* Get the values from the text fields */
	NSString *aContact_date = thisContactList.Contact_date;
	NSString *aNote	= self.textViewNote.text;
	
	/* Create a new instance of contact */
	SSNDBAppDelegate *appDelegate = (SSNDBAppDelegate *)[[UIApplication sharedApplication] delegate];
	if( appDelegate.readSQL == YES ){
		// Save Note
	
		NSString *sqlFileName = @"SSNDB.sqlite";
		NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDir = [documentPaths objectAtIndex:0];
		NSString *sqlFilePath = [documentsDir stringByAppendingPathComponent:sqlFileName];
	
		//sqlite3 init
		sqlite3 *database;
		sqlite3_stmt *statement;
		statement = nil;
		
		if(sqlite3_open([sqlFilePath UTF8String], &database) == SQLITE_OK) {
			NSString *insertSSNDB = [ NSString stringWithFormat: @"update contact SET note=\"%@\" where contect_date=\"%@\"",
										aNote,aContact_date];
			const char *insert_stmt = [insertSSNDB UTF8String];
			sqlite3_prepare_v2(database, insert_stmt,
								-1, &statement, NULL);
			if (sqlite3_step(statement) == SQLITE_DONE) {
				NSLog(@"Update Done");
			}else {
				NSLog(@"Update Failed..");
			}
			sqlite3_finalize(statement);
			sqlite3_close(database);
		}
	}else {
		/* We could not insert a new Person managed object */
		[self 
		 displayAlertWithTitle:NSLocalizedString(@"Edit Note", nil)
		 message:NSLocalizedString(@"Failed To Edit Note XML", nil)];
	}
	
	[self.navigationController popViewControllerAnimated:YES];	
}

/* ------------------------------------------- */
- (void)viewWillAppear:(BOOL)animated{
	NSArray* subs = self.view.subviews;
	id curView;
	for(curView in subs)
	{
		if( [curView conformsToProtocol:@protocol(UITextInputTraits)])
			[curView resignFirstResponder];
	}
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	NSLog(@"%@ %@ %@",thisContactList.SSN, thisContactList.Contact_date, thisContactList.Note);
	//[self.textViewNote setText:contactNote];
	UIBarButtonItem *newEditButton = 
	[[UIBarButtonItem alloc]
	 initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
	 target:self
	 action:@selector(performEdit:)];
	self.editButton = newEditButton;
	[newEditButton release];
	
	UIBarButtonItem *newSaveButton = 
	[[UIBarButtonItem alloc] 
	 initWithTitle:NSLocalizedString(@"Save", nil)
	 style:UIBarButtonItemStylePlain
	 target:self
	 action:@selector(performSaveNote:)];
	self.saveButton = newSaveButton;
	[newSaveButton release];
	
	[self setDefaultNavigationBarButtons];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
	
	self.textViewNote = nil;
	self.thisContactList = nil;
	//self.navigationItem.rightBarButtonItem = nil;
	//self.navigationItem.leftBarButtonItem = nil;
	self.editButton = nil;
	self.saveButton = nil;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[thisContactList release];
	[textViewNote release];
	[editButton release];
	[saveButton release];
    [super dealloc];
}


@end
